<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/1
 * Time: 12:23
 */

namespace zhtfrontend\controllers;

use yii\db\Query;
use zhtfrontend\components\bases\BaseController;
use common\components\helpers\Fun;
use zhtfrontend\models\datas\CommentsScoreHistory;

class PositiveController extends BaseController
{
    public function actionIndex()
    {
        $param = \Yii::$app->request->get();

        $mechanic_ids = (new Query())->select('id')
            ->from('{{%mechanic}}');
        if (isset($param['mechanic_name']) && !empty($param['mechanic_name'])) {
            $mechanic_ids = $mechanic_ids->andWhere(['like', 'name', $param['mechanic_name']]);
        }
        $mechanic_ids = $mechanic_ids->all(Fun::getSiteDb());
        $data = [];
        foreach ($mechanic_ids as $k => $v) {
            $mechanic = (new Query())->select('*')
                ->from('{{%mechanic}}')
                ->where(['id' => $v])
                ->one(Fun::getSiteDb());
            //当月数据
            $comments = (new Query())->select('a.*')
                ->from('{{%comments}} a')
                ->leftJoin('{{%teacher}} b', 'b.id = a.accepter_id')
                ->where(['a.valuator_type' => 1, 'a.accepter_type' => 2, 'b.mechanic_id' => $v['id']])
                ->andWhere(['between', 'a.created_at', strtotime(date('Y-m')), strtotime(date('Y-m-t 23:59:59'))])
                ->all(Fun::getSiteDb());
            //获取当月家长好评率详情
            $score = self::get_parent_satisfy_all($comments);

            //获取当月考核评分
            $score_examine = 0;
            //当月评价详情
            $score_detail = round($score * 0.75 + $score_examine * 0.25, 2);
            //判断是否有上月数据
            $last_month = date('Y-m', strtotime('-1 month'));
            $last_data = (new Query())->select('*')
                ->from('{{%comments_score_history}}')
                ->where(['month' => $last_month, 'type' => 3, 'object_id' => $v['id']])//type = 3,机构评分详情
                ->one(Fun::getSiteDb());
            if (empty($last_data)) {
                //没有上月数据，则查询上月数据写到表里
                $comments_last = (new Query())->select('a.*')
                    ->from('{{%comments}} a')
                    ->leftJoin('{{%teacher}} b', 'b.id = a.accepter_id')
                    ->where(['a.valuator_type' => 1, 'a.accepter_type' => 2, 'b.mechanic_id' => $v['id']])
                    ->andWhere(['between', 'a.created_at', $begin_time = strtotime('-1 month'), strtotime(-date('d') . 'day')])
                    ->all(Fun::getSiteDb());
                //上个月机构总家长好评
                $score_last = self::get_parent_satisfy_all($comments_last);
                //上月考评
                $score_examine_last = 0;
                //上月评价详情
                $score_detail_last = round($score_last * 0.75 + $score_examine_last * 0.25, 2);

                $comments_score_history = new CommentsScoreHistory();
                $comments_score_history->type = 3;
                $comments_score_history->object_id = $v['id'];
                $comments_score_history->score = $score_detail_last;
                $comments_score_history->month = $last_month;
                $comments_score_history->save(false);
            } else {
                $score_detail_last = $last_data['score'];
            }

            $data[$k] = [
                'id' => $v['id'],
                'mechanic_name' => $mechanic['name'],
                'score_detail' => $score_detail,
                'score_detail_last' => $score_detail_last,
            ];
        }

        //本月评分按降序
        if (isset($param['sort']) && $param['sort'] == -1) {
            $sort = array_column($data, 'score_detail');
            array_multisort($sort, SORT_DESC, $data);
        }

        //本月评分按升序
        if (isset($param['sort']) && $param['sort'] == 1) {
            $sort = array_column($data, 'score_detail');
            array_multisort($sort, SORT_ASC, $data);
        }

        //机构当月评分总和
        $mechanic_now = array_sum(array_map(create_function('$val', 'return $val["score_detail"];'), $data));
        $score_detail = round($mechanic_now / count($data), 2);
        //机构上月累计评分总和
        $mechanic_all = array_sum(array_map(create_function('$val', 'return $val["score_detail_last"];'), $data));
        $score_detail_last = round($mechanic_all / count($data), 2);
        return $this->render('index', ['data' => $data, 'score_detail' => $score_detail, 'score_detail_last' => $score_detail_last]);
    }

    /**
     * @return string
     * 二级页面
     * 1、查询该机构的所有老师
     * 2、遍历老师，根据comments的时间，查询当月数据，通过公共方法计算。计算家长好评率
     * 3、查询是否有上个月数据，有则取，没有则查询添加，类似缓存，去本月数据，家长好评率
     * 4、计算考核，取考核数据
     * 5、计算好评详情
     */
    public function actionIndexteacher()
    {
        $param = \Yii::$app->request->get();
        //查询当前机构信息
        $mechanic = (new Query())->select('*')
            ->from('{{%mechanic}}')
            ->where(['id' => $param['mechanic_id']])
            ->one(Fun::getSiteDb());
        $teacher_ids = (new Query())->select('b.id')
            ->from('{{%comments}} a')
            ->leftJoin('{{%teacher}} b', 'a.accepter_id = b.id')
            ->where(['a.valuator_type' => 1, 'a.accepter_type' => 2, 'b.mechanic_id' => $param['mechanic_id']]);
        if (isset($param['teacher_name']) && !empty($param['teacher_name'])) {
            $teacher_id = (new Query())->select('id')
                ->from('{{%teacher}}')
                ->where(['like', 'name', $param['teacher_name']])
                ->column(Fun::getSiteDb());
            $teacher_ids = $teacher_ids->andWhere(['b.id' => $teacher_id]);
        }
        $teacher_ids = $teacher_ids->groupBy('b.id')
            ->column(Fun::getSiteDb());
        $data = [];
        foreach ($teacher_ids as $k => $v) {
            $teacher = (new Query())->select('*')
                ->from('{{%teacher}} a')
                ->where(['id' => $v])
                ->one(Fun::getSiteDb());
            $comments = (new Query())->select('*')
                ->from('{{%comments}}')
                ->where(['valuator_type' => 1, 'accepter_type' => 2, 'accepter_id' => $v])
                ->all(Fun::getSiteDb());
            $now_month = [];
            foreach ($comments as $ck => $cv) {
                if ($cv['created_at'] > strtotime(date('Y-m')) && $cv['created_at'] < strtotime(date('Y-m-t 23:59:59'))) {
                    $now_month[$ck] = $cv;
                }
            }
            //当月
            $teacher_score_now = self::get_score($now_month);
            //累计
            $teacher_score_all = self::get_score($comments);

            //老师类别
            $cate = (new Query())->select('*')
                ->from('{{%cate}}')
                ->where(['id' => $teacher['cate_id']])
                ->one();
            $data[$v] = [
                'id' => $v,
                'teacher_name' => $teacher['name'],
                'img' => $teacher['img'],
                'cate_name' => $cate['name'],
                'teacher_score_now' => $teacher_score_now,
                'teacher_score_all' => $teacher_score_all,
            ];
        }
        //本月评分按降序
        if (isset($param['sort']) && $param['sort'] == -1) {
            $sort = array_column($data, 'teacher_score_now');
            array_multisort($sort, SORT_DESC, $data);
        }

        //本月评分按升序
        if (isset($param['sort']) && $param['sort'] == 1) {
            $sort = array_column($data, 'teacher_score_now');
            array_multisort($sort, SORT_ASC, $data);
        }

        //机构当月评分总和
        $mechanic_now = array_sum(array_map(create_function('$val', 'return $val["teacher_score_now"];'), $data));
        $mechanic_score_now = round($mechanic_now / count($data), 2);
        //机构累计评分总和
        $mechanic_all = array_sum(array_map(create_function('$val', 'return $val["teacher_score_all"];'), $data));
        $mechanic_score_all = round($mechanic_all / count($data), 2);

        return $this->render('indexteacher', ['data' => $data, 'mechanic_score_now' => $mechanic_score_now, 'mechanic_score_all' => $mechanic_score_all, 'mechanic' => $mechanic]);
    }

    /**
     * @return string
     * 三级页面
     */
    public function actionIndexparent()
    {
        $teacher_id = \Yii::$app->request->get('teacher_id');
        $teacher = (new Query())->select('*')
            ->from('{{%teacher}}')
            ->where(['id' => $teacher_id])
            ->one(Fun::getSiteDb());
        $comments = (new Query())->select('*')
            ->from('{{%comments}}')
            ->where(['valuator_type' => 1, 'accepter_type' => 2, 'accepter_id' => $teacher_id])
            ->all(Fun::getSiteDb());
        $now_month = [];
        foreach ($comments as $k => $v) {
            if ($v['created_at'] > strtotime(date('Y-m')) && $v['created_at'] < strtotime(date('Y-m-t 23:59:59'))) {
                $now_month[$k] = $v;
            }
        }
        //评价项
        $comments_info = (new Query())->select('title')
            ->from('{{%comments_info}}')
            ->where(['valuator_type' => 1, 'accepter_type' => 2, 'status' => 1])
            ->orderBy('id asc')
            ->column(Fun::getSiteDb());
        $comments_info[] = '家长满意度';

        //当月学生信息
        $student_data = self::student_manage($now_month);
        //班级总家长满意度
        $class_satisfy = self::class_satisfy($student_data);
        //累计学生信息
        $student_data_all = self::student_manage($comments);
        //累计班级总家长满意度
        $class_satisfy_all = self::class_satisfy($student_data_all);
        //老师当月总评分-家长满意度
        $teacher_now_satisfy = round(array_sum($class_satisfy) / count($class_satisfy), 2);
        //老师累计总评分-家长满意度
        $teacher_all_satisfy = round(array_sum($class_satisfy_all) / count($class_satisfy_all), 2);

        return $this->render('indexparent', [
            'student_data' => $student_data,
            'comments_info' => $comments_info,
            'class_satisfy' => $class_satisfy,
            'teacher' => $teacher,
            'teacher_now_satisfy' => $teacher_now_satisfy,
            'teacher_all_satisfy' => $teacher_all_satisfy,
        ]);
    }

    /**
     * @param $comments
     * @return float
     * 获取所有家长满意度平均值
     */
    public function get_parent_satisfy_all($comments)
    {
        $data = [];
        foreach ($comments as $k => $v) {
            $comments_relations = (new Query())->select('a.comment_id,b.title,a.for_value,b.id')
                ->from('{{%comment_relation}} a')
                ->leftJoin('{{%comments_info}} b', 'a.comment_info_id = b.id')
                ->where(['a.comment_id' => $v['id'], 'b.valuator_type' => 1, 'b.accepter_type' => 2])
                ->orderBy('a.comment_info_id asc')
                ->all(Fun::getSiteDb());
            $data[$v['id']] = $comments_relations;
        }
        $all_satisfy = [];
        foreach ($data as $k => $v) {
            $parent_satisfy = self::get_parent_satisfy_one($v);
            $all_satisfy[$k] = $parent_satisfy;
        }
        $all_satisfy_score = count($all_satisfy) == 0 ? 0 : round(array_sum($all_satisfy) / count($all_satisfy), 2) * 100;
        return $all_satisfy_score;
    }

    /**
     * @param $one_comments_relation
     * @return float|int
     * 获取单课次单人家长满意度
     */
    public function get_parent_satisfy_one($one_comments_relation)
    {
        //获取评价项的计算比重 评价项=>比重
        $proportion = [1 => 0.3, 2 => 0.3, 3 => 0.4];
        $parent_satisfy = 0;
        foreach ($one_comments_relation as $k => $v) {
            $parent_satisfy += $v['for_value'] * $proportion[$v['id']];
        }
        $parent_satisfy = round($parent_satisfy / 4, 2);
        return $parent_satisfy;
    }



    /**
     * @param $comments
     * @return array|float
     * 计算indexteacher\index页面中，总家长满意度等
     */
    public
    function get_score($comments)
    {
        $data = [];
        if (!empty($comments)) {
            foreach ($comments as $k => $v) {
                $comments_relations = (new Query())->select('a.comment_id,b.title,a.for_value')
                    ->from('{{%comment_relation}} a')
                    ->leftJoin('{{%comments_info}} b', 'a.comment_info_id = b.id')
                    ->where(['a.comment_id' => $v['id'], 'b.valuator_type' => 1, 'b.accepter_type' => 2])
                    ->orderBy('a.comment_info_id asc')
                    ->all(Fun::getSiteDb());
                $comments_data = [];
                foreach ($comments_relations as $ck => $cv) {
                    $comments_data[$ck] = [
                        'comment_id' => $cv['comment_id'],
                        'title' => $cv['title'],
                        'for_value' => ($cv['for_value'] / 5) * 100,
                    ];
                }
                //每课次/人次的家长满意度
                $class_score[$k] = self::parent_satisfy($comments_data);
                //总家长满意度
                $data = round(array_sum($class_score) / count($class_score), 2);
            }
        } else {
            return 0;
        }
        return $data;
    }



    /**
     * @param $now_month
     * @return array
     * 获取学生、课程相关信息
     * 1、当月每课次每人的信息-详情部分
     * 2、累计数据/当月数据
     *
     */
    public
    function student_manage($now_month)
    {
        $data = [];
        foreach ($now_month as $k => $v) {
            $student = (new Query())->select('*')
                ->from('{{%student}}')
                ->where(['id' => $v['valuator_id'], 'site_id' => Fun::getSiteId()])
                ->one();
            $class = (new Query())->select('b.lesson,b.class_id,b.title')
                ->from('{{%lesson_students}} a')
                ->leftJoin('{{%class_lesson}} b', 'a.lesson_id = b.lesson_id')
                ->where(['a.id' => $v['lesson_student_id']])
                ->one(Fun::getSiteDb());
            $comments_relations = (new Query())->select('a.comment_id,b.title,a.for_value')
                ->from('{{%comment_relation}} a')
                ->leftJoin('{{%comments_info}} b', 'a.comment_info_id = b.id')
                ->where(['a.comment_id' => $v['id'], 'b.valuator_type' => 1, 'b.accepter_type' => 2])
                ->orderBy('a.comment_info_id asc')
                ->all(Fun::getSiteDb());
            $comments_data = [];
            foreach ($comments_relations as $ck => $cv) {
                $comments_data[$ck] = [
                    'comment_id' => $cv['comment_id'],
                    'title' => $cv['title'],
                    'for_value' => ($cv['for_value'] / 5) * 100,
                ];
            }
            $data['class_data'][$class['class_id']][] = [
                'title' => $class['title'],
                'student_name' => $student['name'],
                'sex' => $student['sex'] == 0 ? '男' : '女',
                'age' => date('Y') - $student['age'],
                'lesson' => $class['lesson'],
                'for_value' => $comments_data,
                'satisfy' => self::parent_satisfy($comments_data),
            ];

            $data['goods_data'] [$class['class_id']] = $class['title'];
        }
        return $data;
    }

    /**
     * @param $data
     * @return int
     * 每课次每人家长满意度计算
     * （（分数*比重）+（分数*比重））/总数
     */
    public
    function parent_satisfy($data)
    {
        if (!empty($data)) {
            $score = 0;
            foreach ($data as $k => $v) {
                $score += $v['for_value'] * 1;
            }
            $data = round($score / count($data), 2);
        } else {
            return 0;
        }
        return $data;
    }

    /**
     * @param student_data
     * @return array
     * 获取班级总家长满意度
     *
     */
    public
    function class_satisfy($student_data)
    {
        $data = [];
        foreach ($student_data['class_data'] as $k => $v) {
            $each_satisfy = 0;
            foreach ($v as $ck => $cv) {
                $each_satisfy += $cv['satisfy'];
            }
            $data[$k] = round($each_satisfy / count($v), 2);
        }
        return $data;
    }
}